#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from config import etc
from utils import log
from utils.file_util import get_100_size_imglink
from utils.session_base import ApiHost, ApiGuest
from utils.session_mc import BaseHandler
from controls import data_user_feed_mysql
from controls import data_topic_note_mysql
from controls import data_topic_title_mysql
from controls import data_topic_note_img_mysql
from controls import data_img_base_mysql


class FeedListHandler(BaseHandler):
    @ApiGuest
    def post(self):
        """
        {begin: 0, limit: 20}

        :return:
            res_list：[
            {
                'optype': 'topic_like',
                'data': {
                    'topicid': 111111111,
                    'title': '马上就要发新版本了'，
                }
            }，
            {
                'optype': 'note_post',
                'data': {
                    'topicid': 1111111111,
                    'topic_title': 'wrdwefsdfsd'
                    'noteid': 22222222222,
                    'note': '马上上当发送到丰盛的范德萨发士大夫',
                    'note_thumbs': ['img1', img2]
                }
            },
            {
                'optype': 'note_like',
                'data': {
                    'topicid': 1111111111,
                    'topic_title': 'wrdwefsdfsd'
                    'noteid': 22222222222,
                    'note': '马上上当发送到丰盛的范德萨发士大夫',
                    'note_thumbs': ['img1', img2]
                }
            }
            ]

        """
        try:
            userid = self.ss_params.get('userid')
            begin = self.ss_params.get('begin', 0)
            limit = self.ss_params.get('limit', 20)
            hide = self.ss_params.get('hide', 0)
            log.i('userid = %s, begin=%s, limit=%s, hide=%s'
                  % (userid, begin, limit, hide))

            if userid and begin and limit and hide is None:
                log.w('params fetching error')
                res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
                self.write(json.dumps(res))
                self.finish()
                return

            noteid_list = []
            topicid_list = []
            res_list = []

            feed_list = data_user_feed_mysql\
                .get_user_feed_list_by_userid(userid, hide, begin, limit)

            for feed in feed_list:
                if feed['optype'] in [
                    data_user_feed_mysql.USER_FEED_TYPE_NOTE_POST,
                    data_user_feed_mysql.USER_FEED_TYPE_NOTE_LIKE,
                ]:
                    # note
                    noteid_list.append(feed['targetid'])
                elif feed['optype'] == data_user_feed_mysql.USER_FEED_TYPE_TOPIC_LIKE:
                    # topic
                    topicid_list.append(feed['targetid'])

            note_map = data_topic_note_mysql\
                .get_topic_note_map_by_noteid_list(noteid_list)

            # note image
            note_img_list = data_topic_note_img_mysql.get_topic_note_img_by_noteid_list(noteid_list)

            all_imgid_list = []
            note_img_list_map = {}
            for item in note_img_list:
                all_imgid_list += item['imgid']
                note_img_list_map[item['noteid']] = item['imgid']

            note_img_map = data_img_base_mysql.get_img_url_by_imgid_list(all_imgid_list)
            note_topic_map = {n['noteid']: n['topicid'] for n in note_map.values()}

            # 合并topic和note对应的topic
            for noteid in note_topic_map:
                topicid_list.append(note_topic_map[noteid])

            topic_map = data_topic_title_mysql\
                .get_topic_title_dict_by_topicid_list(topicid_list)

            for feed in feed_list:
                data = {}
                if feed['optype'] in [
                    data_user_feed_mysql.USER_FEED_TYPE_NOTE_POST,
                    data_user_feed_mysql.USER_FEED_TYPE_NOTE_LIKE,
                ]:
                    # note
                    noteid = feed['targetid']
                    note_item = note_map.get(noteid, None)
                    topicid = note_topic_map.get(noteid, 0)
                    topic_item = topic_map.get(topicid, None)

                    temp_imgid_list = note_img_list_map.get(noteid, [])
                    temp_thumbs = []
                    for imgid in temp_imgid_list:
                        imglink = note_img_map.get(imgid, None)
                        if imglink:
                            temp_thumbs.append(get_100_size_imglink(imglink))

                    data = {
                        'topicid': topicid,
                        'title': topic_item['title'] if topic_item else '',
                        'noteid': noteid,
                        'note': note_item['note'] if note_item else '',
                        'note_thumbs': temp_thumbs,
                    }
                elif feed['optype'] == data_user_feed_mysql.USER_FEED_TYPE_TOPIC_LIKE:
                    # topic
                    topicid = feed['targetid']
                    topic_item = topic_map.get(topicid, None)
                    data = {
                        'topicid': topicid,
                        'title': topic_item['title'] if topic_item else '',
                    }

                res_list.append({
                    'feedid': feed['feedid'],
                    'optype': data_user_feed_mysql.USER_FEED_TYPE_MAP[feed['optype']],
                    'data': data,
                })

            res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': res_list}
            self.write(json.dumps(res))
            self.finish()
            return

        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


class FeedHideSetHandler(BaseHandler):
    @ApiHost
    def post(self):
        feedid_list = self.ss_params.get('feedid')
        userid = self.ss_user['userid']
        hide = self.ss_params.get('hide', 0)

        if feedid_list and userid and hide is None:
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        try:
            if not data_user_feed_mysql.update_user_feed_hide(feedid_list, userid, hide):
                self._generate_res(1, etc.err_500, 'update_feed_hide')
                return

            ret = {'idx': self.ss_idx, 'ret': 0, 'res': {}, 'msg': 'ok'}
            self.write(json.dumps(ret))
            self.finish()
            return
        except Exception as e:
                log.exp(e)
                self._generate_res(1, etc.err_500, 'user_feed_hide')
                return
